package com.gitee.cui.security.oio;

import com.gitee.cui.config.SystemConfig;
import com.gitee.cui.ssl.SSLContextHelper;
import com.gitee.cui.util.IOUtil;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * SSL加密通讯客户端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/5 14:35
 **/
@Slf4j
public class SSLEchoClient {

    static SSLSocket socket;

    static InputStream inputStream;

    static OutputStream outputStream;

    /**
     * 启动服务端
     */
    public static void startClient() {
        try {
            SSLContext context = SSLContextHelper.createClientSSLContext();
            SSLSocketFactory factory = context.getSocketFactory();
            socket = (SSLSocket) factory.createSocket(SystemConfig.SOCKET_SERVER_IP, SystemConfig.SOCKET_SERVER_PORT);
            // 握手时，使用客户端模式
            socket.setUseClientMode(true);
            // 设置要验证对端身份，需验证服务端身份
            socket.setNeedClientAuth(true);
            log.info("连接服务器成功");
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            // 向服务端发送数据
            outputStream.write("client hello\r\n".getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            log.info("sent hello finished!");
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) != -1) {
                log.info("客户端收到：{}", new String(buffer, 0, length));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtil.closeQuietly(inputStream);
            IOUtil.closeQuietly(outputStream);
            IOUtil.closeQuietly(socket);
        }
    }
}
